package com.daxia.ogmall.web.controller.admin;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;

import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.daxia.ogmall.common.Entry;
import com.daxia.ogmall.common.OrderStatus;
import com.daxia.ogmall.common.PayStatus;
import com.daxia.ogmall.common.PayType;
import com.daxia.ogmall.dto.JsonResultDTO;
import com.daxia.ogmall.dto.OrderDTO;
import com.daxia.ogmall.dto.OrderItemDTO;
import com.daxia.ogmall.model.OrderItem;
import com.daxia.ogmall.model.ProductProperties;
import com.daxia.ogmall.model.User;
import com.daxia.ogmall.service.BaseExcelCallback;
import com.daxia.ogmall.service.OrderItemService;
import com.daxia.ogmall.service.OrderService;
import com.daxia.ogmall.support.Page;
import com.daxia.ogmall.util.SpringSecurityUtils;
import com.daxia.ogmall.web.controller.BaseController;

@Controller
@RequestMapping(value = "/admin/order", produces="text/html;charset=UTF-8")
public class AdminOrderController extends BaseController {

	@Autowired
	private OrderService orderService;
	
	@Autowired
	private OrderItemService orderItemService;
	
	@RequestMapping(value = "/myOrder")
	public String myOrder(OrderDTO dto, Map<String, Object> map, Page page) {
		map.put("query", dto);
		return "admin/order/order_myorder";
	}
	
	@RequestMapping(value = "/myOrderList")
	public String myOrderList(OrderDTO dto, Map<String, Object> map, Page page) {
		dto.setUser(new User());
		dto.getUser().setId(getCurrentUserDTO().getId());
		List<OrderDTO> dtos = orderService.find(dto, page);
		map.put("list", dtos);
		map.put("query", dto);
		map.put("pts", PayType.values());
		map.put("oss", OrderStatus.values());
		map.put("pss", PayStatus.values());
		return "admin/order/order_myorder_list";
	}

	@RequestMapping(value = "/subAccountOrder")
	public String subAccountOrder(OrderItemDTO dto, Map<String, Object> map, Page page) {
		dto.setUserId(getCurrentUserDTO().getId());
		List<OrderItemDTO> dtos = orderItemService.findByUser(dto, page);
		List<OrderItemDTO> countDtos = orderItemService.findForCount(dto, null);
		map.put("list", dtos);
		map.put("childrens", countDtos);
		map.put("query", dto);
		map.put("pts", PayType.values());
		map.put("oss", OrderStatus.values());
		map.put("pss", PayStatus.values());
		return "admin/order/order_suborder";
	}
	
	@RequestMapping(value = "/subAccountDetail")
	public String subAccountDetail(OrderItemDTO dto, Map<String, Object> map, Page page) {
		List<OrderItemDTO> dtos = orderItemService.findByUser(dto, page);
		map.put("list", dtos);
		map.put("query", dto);
		map.put("pts", PayType.values());
		map.put("oss", OrderStatus.values());
		map.put("pss", PayStatus.values());
		return "admin/order/order_suborder";
	}
	
	@RequestMapping(value = "/orderDesigner")
	public String orderDesigner(OrderDTO dto, Map<String, Object> map, Page page) {
		return "admin/order/order_designer";
	}
	
	@RequestMapping(value = "/detail")
	public String detail(Map<String, Object> map, Long id) {
		if (id != null) {
			OrderDTO dto = orderService.load(id);
			map.put("n", dto);
		}
		return "admin/order/order_detail";
	}
	
	@ResponseBody
	@RequestMapping(value = "/save")
	
	public String save(OrderDTO dto, JsonResultDTO resultDTO) throws Exception {
		if (dto.getId() == null) {
			orderService.create(dto);
		} else {
			User user = (User) SpringSecurityUtils.getCurrentUser();
			OrderDTO old = orderService.load(dto.getId());
			old.setOrderNo(dto.getOrderNo());
			old.setUser(dto.getUser());
			old.setOperatorUser(user);
			old.setFactoryUser(dto.getFactoryUser());
			old.setCreateTime(dto.getCreateTime());
			old.setPayTime(dto.getPayTime());
			old.setDeliverTime(dto.getDeliverTime());
			old.setAmount(dto.getAmount());
			old.setActualPayAmount(dto.getActualPayAmount());
			old.setPayStatus(dto.getPayStatus());
			old.setStatus(dto.getStatus());
			old.setPayType(dto.getPayType());
			old.setReceiveName(dto.getReceiveName());
			old.setReceiveMobile(dto.getReceiveMobile());
			old.setZipcode(dto.getZipcode());
			old.setProvince(dto.getProvince());
			old.setCity(dto.getCity());
			old.setDistrict(dto.getDistrict());
			old.setAddress(dto.getAddress());
			old.setExpressCompany(dto.getExpressCompany());
			old.setExpressNo(dto.getExpressNo());
			old.setOperatorRemark(dto.getOperatorRemark());
			old.setFactoryRemark(dto.getFactoryRemark());
			old.setInvoiceType(dto.getInvoiceType());
			old.setInvoiceTitle(dto.getInvoiceTitle());
			old.setOrderItems(dto.getOrderItems());
			orderService.updateAllFields(old);
		}
		return okAndClose(resultDTO);
	}

    
	@ResponseBody
	@RequestMapping(value = "/delete") 
	public String delete(Long[] ids, JsonResultDTO resultDTO) throws IOException {
		orderService.deleteByIds(ids);
		return okAndRefresh(resultDTO);
	}
	
	@RequestMapping(value = "/list")
	
	public String list(OrderDTO dto, Map<String, Object> map, Page page) {
		List<OrderDTO> dtos = orderService.find(dto, page);
		map.put("list", dtos);
		map.put("query", dto);
		map.put("pts", PayType.values());
		map.put("oss", OrderStatus.values());
		map.put("pss", PayStatus.values());
		return "admin/order/order_list";
	}
	
	@ResponseBody
	@RequestMapping(value = "/datagrid")
    
    public String datagrid(OrderDTO dto, Map<String, Object> map, Page page) throws Exception {
        List<OrderDTO> dtos = orderService.find(dto, page);
        JSONArray jsonArray = new JSONArray();
        for (OrderDTO order : dtos) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", order.getId());
            jsonObject.put("orderNo", order.getOrderNo());
	        jsonObject.put("user.username", order.getUser().getUsername());    	
	        jsonObject.put("operatorUser.username", order.getOperatorUser().getUsername());    	
	        jsonObject.put("factoryUser.username", order.getFactoryUser().getUsername());    	
			jsonObject.put("createTime", formatDate(order.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));	            	
			jsonObject.put("payTime", formatDate(order.getPayTime(), "yyyy-MM-dd HH:mm:ss"));	            	
			jsonObject.put("deliverTime", formatDate(order.getDeliverTime(), "yyyy-MM-dd HH:mm:ss"));	            	
            jsonObject.put("amount", order.getAmount());
            jsonObject.put("actualPayAmount", order.getActualPayAmount());
            jsonObject.put("payStatus", order.getPayStatus());
            jsonObject.put("status", order.getStatus());
            jsonObject.put("payType", order.getPayType());
            jsonObject.put("receiveName", order.getReceiveName());
            jsonObject.put("receiveMobile", order.getReceiveMobile());
            jsonObject.put("zipcode", order.getZipcode());
            jsonObject.put("address", order.getAddress());
            jsonObject.put("expressCompany", order.getExpressCompany());
            jsonObject.put("expressNo", order.getExpressNo());
            jsonObject.put("operatorRemark", order.getOperatorRemark());
            jsonObject.put("factoryRemark", order.getFactoryRemark());
            jsonObject.put("invoiceType", order.getInvoiceType());
            jsonObject.put("invoiceTitle", order.getInvoiceTitle());
            jsonArray.add(jsonObject);
        }
        JSONObject json = new JSONObject();
        json.put("total", page.getTotalRecords());
        json.put("rows", jsonArray);
        return json.toJSONString();
    }
	
	@ResponseBody
	@RequestMapping(value = "/downExcel")
	public ResponseEntity<byte[]> downExcel(Long id) throws IOException {
		OrderDTO dto=new OrderDTO();
		dto.setId(id);
		String fileName = expExcel(dto);
		if(null!=fileName){
			HttpHeaders headers = new HttpHeaders();
			fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
			headers.setContentDispositionFormData("attachment", fileName);
			headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
			return new ResponseEntity<byte[]>(
					FileUtils
							.readFileToByteArray(new File("/tmp"+"/"
									+ fileName)),
					headers, HttpStatus.CREATED);
		}
		return null;
	}

	public String expExcel(OrderDTO dto) throws IOException {

		List<OrderDTO> dtos = orderService.find(dto, null);
		if(null!=dtos&&dtos.size()>0){
			final OrderDTO order=dtos.get(0);
			final List<OrderItem>  orderItems=order.getOrderItems();
			Entry<String, String> excelEntry = toExcel("/tmp/", "Order_detail", orderItems,
					new BaseExcelCallback<OrderItem>() {

						@Override
						public Row header(Sheet sheet) {
							Workbook wb = sheet.getWorkbook();
							CellStyle style = buildHeaderStyle(wb);
							Row row = sheet.createRow(0);
							row.setHeight((short)800);
							CellUtil.createCell(row, 0, "B2B线上产品销售清单",style);
							Row row2=sheet.createRow(1);
							row2.setHeight((short)800);
							CellUtil.createCell(row2, 0, "客户姓名：",style);
							CellUtil.createCell(row2, 1, order.getUser().getRealName(),style);
							CellUtil.createCell(row2, 4, "订单编号：(市场部填)",style);
							CellUtil.createCell(row2, 5, order.getOrderNo(),style);
							Row row3=sheet.createRow(2);
							row3.setHeight((short)800);
							CellUtil.createCell(row3, 0, "联系电话：",style);
							CellUtil.createCell(row3, 1, order.getUser().getMobile(),style);
							CellUtil.createCell(row3, 4, "收货地址：",style);
							CellUtil.createCell(row3, 5, order.getProvince().getName()+order.getCity().getName()
									+order.getDistrict().getName()+order.getAddress(),style);
							CellUtil.createCell(row3, 9, "备注：",style);
							CellUtil.createCell(row3, 10, "收货人："+order.getReceiveName()+" "+order.getReceiveMobile(),style);
							Row row4=sheet.createRow(3);
							row4.setHeight((short)800);
							int column = 0;
							String[] titles = new String[] { " ", "序号", "品名",
									"图片", "软装大师编号", "规格", "材质", "数量",
									"单位", "B端价","B端价合计","备注(需要特别注意的事项)" };
							for (String title : titles) {
								CellUtil.createCell(row4, column, title, style);
								column += 1;
							}
							return row4;
						}

						@Override
						public Row convert(Workbook wb,Drawing pa,Row row, OrderItem obj) {
							row.setHeight((short)1500);
							createCell(row, 0, " ");
							createCell(row, 1,row.getRowNum()-3	);
							createCell(row, 2, obj.getProduct().getProductCategory().getName());
							String img=new Date().getTime()+".jpg";
							try {
								String images=obj.getProduct().getImages();
								String image=images;
								if(images.indexOf(",")!=-1){
									image=images.split(",")[0];
								}
								//下载图片到临时文件夹
								com.daxia.ogmall.util.FileUtils.downloadImg(image,
										img, "/tmp");
								ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();     
								BufferedImage  bufferImg = ImageIO.read(new File("/tmp"+"/"+img));     
					            ImageIO.write(bufferImg, "jpg", byteArrayOut);
					            int x1=0;
					            int y1=0;
					            int x2=x1+1023;
					            int y2=255;
								HSSFClientAnchor anchor = new HSSFClientAnchor(x1,y1,x2,y2, (short)3, (short)row.getRowNum(), (short)3, row.getRowNum());
						         anchor.setAnchorType(2);
						         pa.createPicture(anchor , wb.addPicture(byteArrayOut.toByteArray(),HSSFWorkbook.PICTURE_TYPE_JPEG));
								
							} catch (Exception e) {
								e.printStackTrace();
								createCell(row, 3, obj.getProduct().getImages());
							}
							createCell(row, 4, " ");
							createCell(row, 5, obj.getSpecification().getSpec1());
							List<ProductProperties> propers=obj.getSpecification().getProductProperties();
							for(ProductProperties pro : propers){
								if("材质".equals(pro.getName())){
									createCell(row, 6, pro.getValue());
									break;
								}
							}
							createCell(row, 7, obj.getQuantity());
							createCell(row, 8, obj.getProduct().getUnit());
							createCell(row, 9, obj.getPayPrice());
							createCell(row, 10, obj.getPayPrice()*obj.getQuantity());
							createCell(row, 11,"");
							return row;
						}

						@Override
						public Row convert(Row row, OrderItem obj) {
							return null;
						}

						@Override
						public Row footer(Sheet sheet) {
							Workbook wb = sheet.getWorkbook();
							CellStyle style = buildHeaderStyle(wb);
							Row row = sheet.createRow(sheet.getLastRowNum()+1);
							row.setHeight((short)800);
							row.setHeight((short)800);
							int totalQuantity=0;
							int totalPay=0;
							for(OrderItem item : orderItems){
								totalQuantity+=item.getQuantity();
								totalPay+=item.getPayPrice()*item.getQuantity();
							}
							CellUtil.createCell(row, 0, "合计：",style);
							CellUtil.createCell(row, 7, totalQuantity+"",style);
							CellUtil.createCell(row, 10, totalPay+"",style);
							Row row2 = sheet.createRow(sheet.getLastRowNum()+1);
							row2.setHeight((short)800);
							Row row3 = sheet.createRow(sheet.getLastRowNum()+1);
							row3.setHeight((short)800);
							CellUtil.createCell(row3, 0, "制单：",style);
							CellUtil.createCell(row3, 3, "财务：",style);
							CellUtil.createCell(row3, 5, "采购：",style);
							return row3;
						}

						
					});
			return excelEntry.getKey();
		}
		return null;
	}
}
